from flask import Flask, render_template, url_for, session, redirect, request
from werkzeug.datastructures import CombinedMultiDict
from . import usercenter
from app.models import User, Oplog, db
from .forms import UserForm
import os
import datetime
from ...blueprint import BASE_DIR
import time


@usercenter.route('/', methods=('GET', 'POST'))
def usercenter1():
    path = BASE_DIR + "/static/img/userimg/"
    print('usercenter函数开始')
    form = UserForm()
    print(form.validate_on_submit())
    if request.method == "GET":
        u = User.query.filter_by(user_name=session['username']).first()
        print(u.pimg)
        return render_template('usercenter.html', form=form, click1=3, click2=2, click3=5, click4=7, click5=1, user=u)
    else:
        form = UserForm(CombinedMultiDict([request.form, request.files]))
        u = User.query.filter_by(user_name=session['username']).first()
        print('POST')
        if form.validate_on_submit():
            if form.data['pwd'] == form.data['pwd2']:
                username = u.user_name
                psw = form.data['pwd']
                mail = form.data['mail']
                upload_image = form.data["image"]
                filename = time.strftime("%Y%m%d", time.localtime()) + ".jpg"
                file_path = path + filename
                upload_image.save(file_path)
                pimg = "img/userimg/" + filename
                u.user_password = psw
                u.email = mail
                u.pimg = pimg
                ip = request.remote_addr
                opuser = u.user_name
                op1 = "Change information"
                date = datetime.datetime.now()
                opt = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
                db.session.add(opt)
                db.session.commit()
                return redirect("../")
            else:
                return '两次输入的密码不一致'
        else:
            print(form.form_errors)
            return "修改失败"


@usercenter.route('/zhuxiao', methods=('GET', 'POST'))
def zhuxiao():
    ip = request.remote_addr
    opuser = session['username']
    op1 = "User Log Out"
    date = datetime.datetime.now()
    OPT = Oplog(op_user=opuser, op=op1, IP=ip, op_date=date)
    db.session.add(OPT)
    db.session.commit()
    session['username'] = None
    return redirect('../')